/**
 * Copyright (c) 2019-2029, wwww.kiwipeach.cn (liuburu@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package open.kiwipeach.autoconfigure.web.interceptor;

import cn.kiwipeach.blog.mapper.CustomBlogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 描述：博客详情查看浏览量拦截器
 *
 * @author kiwipeach
 * @since 1.0
 */
@Slf4j
public class BlogViewCountInterceptor implements HandlerInterceptor {

    private CustomBlogMapper customBlogMapper;
    private Cache cache;

    public BlogViewCountInterceptor(CustomBlogMapper customBlogMapper, Cache cache) {
        this.customBlogMapper = customBlogMapper;
        this.cache = cache;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestUri = request.getRequestURI();
        String[] requstStrs = requestUri.split("/");
        String blogId = requstStrs[3];
        String cacheKey = String.format("%s-%s", request.getSession().getId(), blogId);
        if (Objects.isNull(cache.get(cacheKey))) {
            //1分钟缓存
            Integer integer = customBlogMapper.updateBlogViewCountByBlogId(blogId);
            cache.put(cacheKey, integer);
            log.info("博客(id:{})浏览量:+{}", blogId, integer);
        }
        return true;
    }
}
